package com.sander.guardmanagement.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.content.res.AssetManager;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.etsy.android.grid.StaggeredGridView;

import com.sander.guardmanagement.R;
import com.sander.guardmanagement.db.CityDB;
import com.sander.guardmanagement.http.BaseCallback;
import com.sander.guardmanagement.http.HomeGetCity;
import com.sander.guardmanagement.http.HomegetHotCitys;
import com.sander.guardmanagement.http.OkHttpHelper;
import com.sander.guardmanagement.model.City;
import com.sander.guardmanagement.response.ResponseHomeGetCity;
import com.sander.guardmanagement.response.ResponseHomeGetCityData;
import com.sander.guardmanagement.response.ResponseHomegetHotCitys;
import com.sander.guardmanagement.response.ResponseHomegetHotCitysData;
import com.sander.guardmanagement.ui.view.CityListAdapter;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import pub.devrel.easypermissions.EasyPermissions;

public class CityListActivity extends AppCompatActivity {


    private List<ResponseHomegetHotCitysData> city_list = new ArrayList<>();

    private Map<String,City> cityMap = new HashMap<>();
    public CityListAdapter cityListAdapter;

    private final int RC_SETTINGS_SCREEN = 125;
    private final int RC_LOCATION_CONTACTS_PERM = 124;
    private AMapLocationClient mLocationClient;
    String[] perms = {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE};

    private TextView localCityTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_city_list);
        initCallBack();
        initData();
        initView();
        initLocation();
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);

    }

    private void initCallBack(){
        FrameLayout frameLayout = (FrameLayout) findViewById(R.id.callbackLayout);
        frameLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void initData(){
        final CityDB cityDB = openCityDB();
        List<City> list= cityDB.getAllCity();
        for (int i = 0; i < list.size();i ++){
            City city = list.get(i);
            this.cityMap.put(city.getProvince(),city);
        }
        HomegetHotCitys homeGetCity = new HomegetHotCitys();
        OkHttpHelper.getinstance().post(homeGetCity.requestUrl(), homeGetCity.getValueOfClas(), new BaseCallback<ResponseHomegetHotCitys>() {
            @Override
            public void onRequestBefore() {

            }

            @Override
            public void onFailure(Request request, Exception e) {
                Log.d("sander","get error");
            }

            @Override
            public void onSuccess(Response response, ResponseHomegetHotCitys o) {
                Log.d("sander","get citys " + o.getMsg());
                if (o.getCode() == 0){
                    city_list = o.getData();
                    updateData();
                }
            }

            @Override
            public void onError(Response response, int errorCode, Exception e) {

            }
        });
    }
    public void updateData()
    {
        if (cityListAdapter != null){
            cityListAdapter.list = this.city_list;
            cityListAdapter.notifyDataSetChanged();
            int row = this.city_list.size() / 3;
            int section = this.city_list.size() %3;
            if (section > 0){
                row += 1;
            }
            StaggeredGridView listView = (StaggeredGridView) findViewById(R.id.citylistview);

            ViewGroup.LayoutParams params = listView.getLayoutParams();
            params.height = row * 100 + 60;
            listView.setLayoutParams(params);
        }
    }



    private void initView(){
        StaggeredGridView listView = (StaggeredGridView) findViewById(R.id.citylistview);

        cityListAdapter = new CityListAdapter(this,this.city_list);

        listView.setAdapter(cityListAdapter);
        ViewGroup.LayoutParams params = listView.getLayoutParams();

        int row = this.city_list.size() / 3;
        int section = this.city_list.size() %3;
        if (section > 0){
            row += 1;
        }
        params.height = row * 100 + 60;
        listView.setLayoutParams(params);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ResponseHomegetHotCitysData city = city_list.get(position);
                onClickCity(city);
            }
        });


        localCityTextView = (TextView)findViewById(R.id.getlocaladress);
        localCityTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ResponseHomegetHotCitysData city = new ResponseHomegetHotCitysData();
                city.city_name = localCityTextView.getText().toString();
                city.city_id = -1;
                onClickCity(city);
            }
        });
        localCityTextView.setEnabled(false);

    }

    public void initLocation(){
        //高德定位
        mLocationClient = new AMapLocationClient(this);
        AMapLocationClientOption option = new AMapLocationClientOption();
        option.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        option.setOnceLocation(true);
        mLocationClient.setLocationOption(option);
        mLocationClient.setLocationListener(new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation aMapLocation) {
                if (aMapLocation != null) {
                    if (aMapLocation.getErrorCode() == 0) {
                        String city = aMapLocation.getCity();
                        String district = aMapLocation.getDistrict();
                        Log.e("onLocationChanged", "city: " + city);
                        Log.e("onLocationChanged", "district: " + district);
                        localCityTextView.setText(city);
                        localCityTextView.setEnabled(true);
                    } else {
                        //定位失败
                        localCityTextView.setText("定位失败");
                        localCityTextView.setEnabled(false);
                    }
                }
            }
        });

        //权限判断
        if (EasyPermissions.hasPermissions(this, perms)) {

            mLocationClient.startLocation();
        } else {
            // Ask for both permissions
            EasyPermissions.requestPermissions(this, "定位需要相关权限",
                    RC_LOCATION_CONTACTS_PERM, perms);
        }
    }

    private void onClickCity(ResponseHomegetHotCitysData city){
        Intent intent = new Intent(CityListActivity.this,DistrictListActivity.class);
        //用Bundle携带数据
        Bundle bundle=new Bundle();
        bundle.putSerializable("city",city);
        intent.putExtras(bundle);
        startActivity(intent);
    }
    private CityDB openCityDB(){
        AssetManager assetManager = getApplicationContext().getAssets();

        String path = "/data"
                + Environment.getDataDirectory().getAbsolutePath()
                + File.separator + "com.sander.guardmanagement" + File.separator
                + CityDB.CITY_DB_NAME;
        File db = new File(path);
        Log.d("sander","db path = " + path);
        if (!db.exists()){
            if (!db.exists()) {
                // L.i("db is not exists");
                try {
                    InputStream is = assetManager.open("city.db");
                    FileOutputStream fos = new FileOutputStream(db);
                    int len = -1;
                    byte[] buffer = new byte[1024];
                    while ((len = is.read(buffer)) != -1) {
                        fos.write(buffer, 0, len);
                        fos.flush();
                    }
                    fos.close();
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return new CityDB(this,path);
    }
}
